package com.frejoys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.ReasonAddDto;
import com.frejoys.common.dto.admin.ReasonListDto;
import com.frejoys.common.dto.admin.ReasonUpDto;
import com.frejoys.dao.entity.Reason;
import com.frejoys.dao.mapper.ReasonMapper;
import com.frejoys.service.ReasonService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ReasonServiceImpl  extends ServiceImpl<ReasonMapper, Reason> implements ReasonService {
    @Override
    public Reason getInfo(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean addInfo(ReasonAddDto dto) {
        return save(new Reason(){{
            setContent(dto.getContent());
            setType(dto.getType());
        }});
    }

    @Override
    public boolean upInfo(ReasonUpDto dto) {
        LambdaUpdateWrapper<Reason> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Reason::getId, dto.getId());
        if (StrUtil.isNotEmpty(dto.getContent())) {
            wrapper.set(Reason::getContent, dto.getContent());
        }
        if (dto.getType()!=null) {
            wrapper.set(Reason::getType, dto.getType());
        }
        return update(wrapper);
    }

    @Override
    public List<Reason> listInfo(Integer type) {
        LambdaQueryWrapper<Reason> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reason::getType,type);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Reason> listInfo(ReasonListDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);
        LambdaQueryWrapper<Reason> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getType()!=null,Reason::getType,dto.getType());
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getContent()),Reason::getContent,dto.getContent());
        return baseMapper.selectPage(page, queryWrapper).getRecords();
    }

    @Override
    public Map<Integer, String> getIdNameMap(List<Integer> ids) {
        LambdaQueryWrapper<Reason> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Reason::getId,Reason::getContent);
        wrapper.in(!CollectionUtils.isEmpty(ids),Reason::getId,ids);
        List<Reason> categories = baseMapper.selectList(wrapper);
        return categories.stream().collect(Collectors.toMap(Reason::getId,Reason::getContent));
    }
}
